<?php 
/*
 * Sequence Synonyms
 *
 * Copyright (c) 2009 Victor de la Torre (vdelatorre@cnio.es)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * http://code.google.com/p/ssynonyms/
 *
 */
 
 class Rest {
    
	 /**
	 * parseRestUrl function.
	 * 
	 * @access public
	 * @param mixed $param
	 * @return void
	 */
	function _parseUrl($url){
		  		
 		if (!$url)
			return false;
		
		$u = parse_url($url);
		
  		return $u;
	}
	
	
    /**
     * getProxyResponse function.
     * 
     * @access public
     * @param mixed $param
     * @return void
     */
    function getProxyResponse($url){
    
		if (!$u = $this->_parseUrl($url))
			return false;	
		
		$buf = $this->_buildPOST($u);
		
		$fp = @fsockopen ($u['host'], 80);
		stream_set_timeout($fp, 100);
	
		if (!$fp)
			return false;

		fputs($fp, $buf);

		$content = "";

	    do {
		    $line = fgets($fp);
		    //echo $line.'<br>';
		    if ($line === false)
		       break; 
		    if (preg_match('/^ /',$line) or preg_match('/^</',$line) or preg_match('/>/',$line) or strlen($line) >40){
		    	if (!preg_match('/^</',$line))
		    		$content = trim($content);
		    	$content.= $line;   	
		    }   
		    	
 	    } while(true);
	
		fclose($fp);
		
		if (!$content)
			return false;

		return $content;
	}

 
	/**
	 * buildPOST function.
	 * 
	 * @access public
	 * @param mixed $u
	 * @return void
	 */
	function _buildPOST($u){
		
		$buf  = "POST ".$u['path']." HTTP/1.0\r\n";
		$buf .= "Host: ".$u['host']."\r\n";
		$buf .= "Content-type: application/x-www-form-urlencoded; charset=UTF-8\r\n";
		$buf .= "Content-length: ".strlen($u['query'])."\r\n";
		$buf .= "\r\n";
		$buf .= $u['query'];
		
		//echo $buf;
		
		return $buf;
	}
	
	/**
	 * buildGET function.
	 * 
	 * @access public
	 * @param mixed $u
	 * @return void
	 */
	function _buildGET($u){
		
		$buf  = "GET ".$u['path'].'?'.$u['query']." HTTP/1.1\r\n";
		$buf .= "Host: ".$u['host']."\r\n";
		$buf .= "Connection: Close\r\n\r\n";

		return $buf;

	}
}	
?>